//
//  DHOrderPayViewController.m
//  Dresshere
//
//  Created by ZhangPeng on 2018/1/17.
//  Copyright © 2018年 张朋. All rights reserved.
//

#import "DHOrderPayViewController.h"
#import <BeeCloud/BeeCloud.h>
#import "DHOrderManagerViewController.h"

@interface DHOrderPayViewController ()<BeeCloudDelegate>

@property (weak, nonatomic) IBOutlet UIView *bottomView;
@property (weak, nonatomic) IBOutlet UILabel *discountsLabel;
@property (weak, nonatomic) IBOutlet UILabel *priceLabel;
@property (weak, nonatomic) IBOutlet UILabel *totalLabel;
@property (weak, nonatomic) IBOutlet UIImageView *wechat;
@property (weak, nonatomic) IBOutlet UIImageView *alipay;
@property (weak, nonatomic) IBOutlet DHGradualButton *ensureButton;

@property (assign, nonatomic) PayChannel channel;
@property (assign, nonatomic) CGFloat totalPrice;

@property (strong, nonatomic) NSArray *ordersArray;
@property (strong, nonatomic) NSMutableDictionary *orderValidParams;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *topSafeViewLayout;

@end

@implementation DHOrderPayViewController

- (NSArray *)ordersArray{
    if (!_ordersArray) {
        _ordersArray = [NSArray array];
    }
    return _ordersArray;
}

- (NSMutableDictionary *)orderValidParams{
    if (!_orderValidParams) {
        _orderValidParams = [NSMutableDictionary dictionary];
    }
    return _orderValidParams;
}

- (instancetype)initWithOrders:(NSArray *)ordersArr orderValidParams:(NSMutableDictionary *)orderValidParams
{
    self = [super init];
    if (self) {
        self.ordersArray = ordersArr;
        self.orderValidParams = orderValidParams;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"支付";
    
    self.channel = PayChannelWxApp;
    
    if ([UIDevice systemVersion] < 11) {
        self.topSafeViewLayout.constant = 20;
    }
    
    [self setupUI];
    [self actions];
    
    [BeeCloud setBeeCloudDelegate:self];
}

- (void)setupUI{
    self.view.backgroundColor = [UIColor whiteColor];
    self.bottomView.layer.cornerRadius = 2;
    self.bottomView.layer.shadowColor = [[UIColor blackColor] CGColor];
    self.bottomView.layer.shadowRadius = 5;
    self.bottomView.layer.shadowOpacity = 0.5;
    self.bottomView.layer.shadowOffset  = CGSizeMake(0, 0);
    
    __block CGFloat totalPrice = 0;
    [self.ordersArray enumerateObjectsUsingBlock:^(NSDictionary *obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSArray *costs = [obj objectForKey:@"costs"];
        [costs enumerateObjectsUsingBlock:^(NSDictionary *obj, NSUInteger idx, BOOL * _Nonnull stop) {
            CGFloat cost_value = [[obj objectForKey:@"cost_value"] floatValue];
            if (cost_value >= 0) {
                totalPrice += cost_value;
            }else{
                totalPrice -= cost_value;
            }
        }];
    }];
    self.totalPrice = totalPrice;
    self.priceLabel.text = [NSString stringWithFormat:@"￥%.2f", totalPrice];
}

- (void)actions{
    __weak typeof(self) weakself = self;
    [self.wechat bk_whenTapped:^{
        [weakself.wechat setImage:[UIImage imageNamed:@"pay_selected"]];
        [weakself.alipay setImage:[UIImage imageNamed:@"pay_unselected"]];
        weakself.channel = PayChannelWxApp;
    }];
    [self.alipay bk_whenTapped:^{
        [weakself.wechat setImage:[UIImage imageNamed:@"pay_unselected"]];
        [weakself.alipay setImage:[UIImage imageNamed:@"pay_selected"]];
        weakself.channel = PayChannelAliApp;
    }];
    
    [self.ensureButton addTarget:self action:@selector(ensureAction:) forControlEvents:UIControlEventTouchUpInside];
}

- (void)ensureAction:(UIButton *)sender {
    
    // 对订单进行验证
    [[DHNetAPIClient shareDHNetAPIClient] request_orders_validWithParams:self.orderValidParams andBlock:^(id data, NSError *error) {
        NSString *billno = [self genBillNo];
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        [dict setObject:@"ORDER" forKey:@"payment_type"];
        [dict setObject:[[self.ordersArray objectAtIndex:0] objectForKey:@"_id"] forKey:@"order_id"];
        
        BCPayReq *payReq = [[BCPayReq alloc] init];
        payReq.channel = self.channel; //支付渠道
        payReq.title = [BeeCloud getCurrentMode] ? @"iOS Demo Sandbox" : @"Dresshere";; //订单标题
        payReq.totalFee = [NSString stringWithFormat:@"%.0f",self.totalPrice*100]; //订单价格
        payReq.billNo = billno; //商户自定义订单号
        payReq.scheme = @"dresshere"; //URL Scheme,在Info.plist中配置;
        payReq.billTimeOut = 300; //订单超时时间
        payReq.viewController = self; //银联支付和Sandbox环境必填
        payReq.optional = dict;//商户业务扩展参数，会在webhook回调时返回
        [BeeCloud sendBCReq:payReq];
    }];
}

#pragma mark - BeeCloudDelegate
- (void)onBeeCloudResp:(BCBaseResp *)resp{
    switch (resp.type) {
        case BCObjsTypePayResp:
        {
            // 支付请求响应
            BCPayResp *tempResp = (BCPayResp *)resp;
            if (tempResp.resultCode == 0) {
                // 支付成功
                BCPayReq *payReq = (BCPayReq *)resp.request;
                [NSObject showHudTipStr:resp.resultMsg];
                DHOrderManagerViewController *omController = [[DHOrderManagerViewController alloc] init];
                [self.navigationController pushViewController:omController animated:YES];
            } else {
                //支付取消或者支付失败
                [NSObject showHudTipStr:[NSString stringWithFormat:@"%@ : %@",tempResp.resultMsg, tempResp.errDetail]];
            }
            [self dismissViewControllerAnimated:NO completion:nil];
            [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
        }
            break;
        case BCObjsTypeQueryBillsResp:
        {
            BCQueryBillsResp *tempResp = (BCQueryBillsResp *)resp;
            if (resp.resultCode == 0) {
                if (tempResp.count == 0) {
                    [NSObject showHudTipStr:@"未找到相关订单信息"];
                } else {
                    //                    self.orderList = tempResp;
                    //                    [self performSegueWithIdentifier:@"queryResult" sender:self];
                }
            } else {
                [NSObject showHudTipStr:[NSString stringWithFormat:@"%@ : %@",tempResp.resultMsg, tempResp.errDetail]];
            }
        }
            break;
        case BCObjsTypeQueryRefundsResp:
        {
            BCQueryRefundsResp *tempResp = (BCQueryRefundsResp *)resp;
            if (resp.resultCode == 0) {
                if (tempResp.count == 0) {
                    [NSObject showHudTipStr:@"未找到相关订单信息"];
                } else {
                    //                    self.orderList = tempResp;
                    //                    [self performSegueWithIdentifier:@"queryResult" sender:self];
                }
            } else {
                [NSObject showHudTipStr:[NSString stringWithFormat:@"%@ : %@",tempResp.resultMsg, tempResp.errDetail]];
            }
        }
            break;
            
        case BCObjsTypeOfflinePayResp:
        {
//            BCOfflinePayResp *tempResp = (BCOfflinePayResp *)resp;
//            if (resp.resultCode == 0) {
//                BCOfflinePayReq *payReq = (BCOfflinePayReq *)tempResp.request;
//                switch (payReq.channel) {
//                    case PayChannelAliOfflineQrcode:
//                    case PayChannelWxNative:
//                    case PayChannelBCNative:
//                    case PayChannelBCAliQrcode:
//                        if (tempResp.codeurl.isValid) {
//                            //                            QRCodeViewController *qrCodeView = [[QRCodeViewController alloc] init];
//                            //                            qrCodeView.resp = tempResp;
//                            //                            qrCodeView.delegate = self;
//                            //                            [self.navigationController pushViewController:qrCodeView animated:YES];
//                        }
//                        break;
//                    case PayChannelAliScan:
//                    case PayChannelWxScan:
//                    case PayChannelBCWxScan:
//                    case PayChannelBCAliScan:
//                    {
//                        BCOfflineStatusReq *req = [[BCOfflineStatusReq alloc] init];
//                        req.channel = payReq.channel;
//                        req.billNo = payReq.billNo;
//                        [BeeCloud sendBCReq:req];
//                    }
//                        break;
//                    default:
//                        break;
//                }
//            } else {
//                [NSObject showHudTipStr:[NSString stringWithFormat:@"%@ : %@",tempResp.resultMsg, tempResp.errDetail]];
//            }
        }
            break;
        case BCObjsTypeOfflineBillStatusResp:
        {
//            static int queryTimes = 1;
//            BCOfflineStatusResp *tempResp = (BCOfflineStatusResp *)resp;
//            if (tempResp.resultCode == 0) {
//                if (!tempResp.payResult && queryTimes < 3) {
//                    queryTimes++;
//                    [BeeCloud sendBCReq:tempResp.request];
//                } else {
//                    [NSObject showHudTipStr:tempResp.payResult?@"支付成功":@"支付失败"];
//                    //                BCOfflineRevertReq *req = [[BCOfflineRevertReq alloc] init];
//                    //                req.channel = tempResp.request.channel;
//                    //                req.billno = tempResp.request.billno;
//                    //                [BeeCloud sendBCReq:req];
//                    queryTimes = 1;
//                }
//
//            } else {
//                [NSObject showHudTipStr:[NSString stringWithFormat:@"%@ : %@",tempResp.resultMsg, tempResp.errDetail]];
//            }
        }
            break;
        case BCObjsTypeOfflineRevertResp:
        {
#pragma mark - 线下撤销订单响应事件类型，包含WX_SCAN,ALI_SCAN,ALI_OFFLINE_QRCODE
//            BCOfflineRevertResp *tempResp = (BCOfflineRevertResp *)resp;
//            if (resp.resultCode == 0) {
//                [NSObject showHudTipStr:tempResp.revertStatus?@"撤销成功":@"撤销失败"];
//            } else {
//                [NSObject showHudTipStr:[NSString stringWithFormat:@"%@ : %@",tempResp.resultMsg, tempResp.errDetail]];
//            }
        }
            break;
        default:
        {
            if (resp.resultCode == 0) {
                [NSObject showHudTipStr:resp.resultMsg];
            } else {
                [NSObject showHudTipStr:[NSString stringWithFormat:@"%@ : %@",resp.resultMsg, resp.errDetail]];
            }
        }
            break;
    }
}

#pragma mark - 生成订单号
- (NSString *)genBillNo {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyyMMddHHmmssSSS"];
    return [formatter stringFromDate:[NSDate date]];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
